/*************************************************************
 * File: InitialServlet.java
 * Copyright (c) 2012
 * Author: Huang Shaobin
 * Email: Shaobin.Software@gmail.com Shaobin_Software@163.com 
 * Date: Mar 1, 2013
 * Description: 
 ************************************************************/

package snow.core.web;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HttpServletBean;

import snow.core.exceptions.BusinessException;
import snow.core.security.SecurityService;

/**
 * 初始化的Servlet
 * 
 * @author Shaobin.Software@gmail.com Shaobin_Software@163.com
 * @version 1.0
 */
@SuppressWarnings("serial")
public class InitialServlet extends HttpServletBean {

	private final Log log = LogFactory.getLog(getClass());

	private String securityServiceName = "securityService";

	/**
	 * 初始化权限信息
	 * @throws BusinessException 
	 */
	protected void initPermissions() throws BusinessException {
		try {
			log.info("开始初始化权限信息……");
			lookupBeanFrom(securityServiceName, SecurityService.class).initializePermission();
		} finally {
			log.info("结束初始化权限信息！");
		}
	}

	public void initServletBean() throws ServletException {
		try {
			log.info("开始初始化……");
			initPermissions();
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
		} finally {
			log.info("结束初始化！");
		}
	}

	protected ApplicationContext lookupApplicationContext() {
		return lookupApplicationContextFrom(getServletContext());
	}

	protected ApplicationContext lookupApplicationContextFrom(ServletContext context) {
		return WebApplicationContextUtils.getWebApplicationContext(context);
	}

	protected <T> T lookupBeanFrom(String beanName, Class<T> beanClass) {
		return lookupApplicationContext().getBean(beanName, beanClass);
	}

	public String getSecurityServiceName() {
		return this.securityServiceName;
	}

	public void setSecurityServiceName(String securityServiceName) {
		this.securityServiceName = securityServiceName;
	}

}
